import clr
import System
clr.AddReference('Microsoft.Scripting.dll')
import Microsoft

class _C:
    def _m(self): pass
ClassType = type(_C)

def IsPythonClass(object):
    return isinstance(object, ClassType) or hasattr(object, '__bases__')

def IsInstanceOfClr(obj, cls):
	return clr.GetClrType(cls).IsAssignableFrom(type(obj))

def IsSubclassOfClr(cls1, cls2):
	return clr.GetClrType(cls1).IsSubclassOf(cls2)

def IsDynamic(obj):
	return IsInstanceOfClr(obj, Microsoft.Scripting.IDynamicObject)

def GetClrType(t):
	mytype = type(t)
	knowntype = type(1)
	if mytype == type(knowntype):
		return clr.GetClrType(t)
	if mytype == type(clr.GetClrType(knowntype)):
		return t
	raise RuntimeError, 'Not a CLR type: ' + repr(t)

def ClrAttribute(attribute):
	if not IsSubclassOfClr(attribute, System.Attribute):
		raise RuntimeError, 'Not a CLR attribute'
	def ClrAttribute(fn):
		if not hasattr(fn, 'clr_attributes'):
			fn.clr_attributes = []
		fn.clr_attributes.append((attribute, ))
		fn.clr_method = True
		return fn
	return ClrAttribute

def ClrAccepts(*arguments):
	def ClrAccepts(fn):
		fn.clr_accepts = map(GetClrType, arguments)
		fn.clr_method = True
		return fn
	return ClrAccepts

def ClrReturns(returnType):
	def ClrReturns(fn):
		fn.clr_returns = GetClrType(returnType)
		fn.clr_method = True
		return fn
	return ClrReturns

class clr_property(property):
	def __init__(self, get_fn, set_fn=None, del_fn=None, docstring=None):
		property.__init__(self, get_fn, set_fn, del_fn, docstring)

def ClrProperty(propertyType, get_fn, set_fn=None):
	result = clr_property(get_fn, set_fn, None, None)
	result.propertyType = propertyType
	return result
